﻿#region Regions

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

#endregion

namespace FMWare.Core.Base
{
	public abstract class Collection<T> : Dictionary<int, T> where T : Item, new()
	{
		#region Declarations

		protected Dictionary<int, T> _uniqueIdView;

		#endregion

		#region Constructors

		protected Collection(int capacity) : base(capacity) {}

		#endregion

		#region Public Properties

		public Int32 RecordCount { get; protected set; }

		#endregion

		#region Internal Properties

		internal abstract string ExportHeader { get; }

		#endregion

		#region Protected Properties

		protected bool UseUniqueIdView { get; set; }

		#endregion

		#region Internal Methods

		internal void Export(string fileName)
		{
			fileName = string.Format(fileName, typeof (T).Name);
			StreamWriter writer = new StreamWriter(fileName, false, Encoding.Unicode);
			writer.WriteLine(ExportHeader);
			for (int i = 0; i < RecordCount; i++)
				writer.WriteLine(this[i].ExportData);
			writer.Close();
		}


		/// <summary>
		/// Reads the data with the specified reader.
		/// </summary>
		/// <param name="reader">The reader.</param>
		internal virtual void Read(BinaryReader reader)
		{
			RecordCount = reader.ReadInt32();
			_uniqueIdView = new Dictionary<int, T>(RecordCount);

			for (int i = 0; i < RecordCount; i++)
			{
				T item = new T();
				item.Read(reader);

				Add(item.UniqueId, item);
			}
		}

		/// <summary>
		/// Writes the data with specified writer.
		/// </summary>
		/// <param name="writer">The writer.</param>
		internal virtual void Write(BinaryWriter writer)
		{
			writer.Write(Count);

			foreach (T item in Values)
				item.Write(writer);
		}

		#endregion
	}
}